package com.yogee.topseller.activity.my;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.bean.PersonalDataBean;
import com.yogee.topseller.bean.UpdateInfoBean;
import com.yogee.topseller.bean.UpdatePhotoBean;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.layout.PersonalDataMenuLayout;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.FileStorage;
import com.yogee.topseller.utils.GlideUtils;
import com.yogee.topseller.utils.NeedPermissions;
import com.yogee.topseller.view.VoucherPop;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PersonalDataActivity extends HttpActivity implements VoucherPop.OnIdCardPopClickListener{
    @BindView(R.id.personal_data_bg_iv)
    ImageView personalDataBgIv;
    @BindView(R.id.personal_data_photo_iv)
    ImageView photoIv;
    @BindView(R.id.personal_data_name_tv)
    TextView nameTv;
    @BindView(R.id.personal_data_meun_layout)
    PersonalDataMenuLayout meunLayout;
    @BindView(R.id.personal_data_bg)
    View bg;
    private int GALLERY_RESULT = 150;
    private int CAMERA_RESULT = 100;

    private File photoFile;
    private String userid;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_data;
    }

    @Override
    protected void initView() {
        userid = AppUtil.getUserId(this);
        Log.d("asjdsad", userid + "");
    }

    @Override
    protected void onResume() {
        super.onResume();
        userid = AppUtil.getUserId(this);
        personalData(userid);
    }

    @OnClick({R.id.my_sure_tv, R.id.personal_data_photo_rl, R.id.personal_data_setting_iv, R.id.personal_data_back_rl, R.id.personal_data_photo_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.personal_data_photo_rl://头像
                break;
            case R.id.personal_data_setting_iv://设置
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.personal_data_back_rl://返回
                finish();
                break;
            case R.id.personal_data_photo_iv://修改头像
                if (AppUtil.isExamined(this)) {
                    replacePhoroOrCorver();
                }
                break;
            case R.id.my_sure_tv://确定按钮
//                finish();
                updateInfo();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "部分所需权限未开启，将影响功能正常使用，请开启权限！", Toast.LENGTH_LONG).show();
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_RESULT && resultCode == RESULT_OK) {
            updatePhoto(userid, photoFile);
        }
        if (requestCode == GALLERY_RESULT && resultCode == RESULT_OK) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            updatePhoto(userid, new File(picturePath));
        }
    }

    public void replacePhoroOrCorver() {
        List<String> permissions = new NeedPermissions(this).cameraPermissions();
        if (permissions.size() > 0) {
            String[] permission = new String[permissions.size()];
            for (int i = 0; i < permissions.size(); i++) {
                permission[i] = permissions.get(i);
            }
            ActivityCompat.requestPermissions(this, permission, 1);
        } else {
            new VoucherPop(bg, this, this).idCardPop();
        }
    }

    @Override
    public void onCameraClick() {
        toCamera();
    }

    @Override
    public void onAlbumClick() {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, GALLERY_RESULT);
    }

    public void toCamera() {
        Intent intent = new Intent();
        Uri uri;
        File file = new FileStorage().createIconFile();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, "com.yogee.topseller.fileprovider", file);//通过FileProvider创建一个content类型的Uri
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//将拍取的照片保存到指定URI
        photoFile = file;
        startActivityForResult(intent, CAMERA_RESULT);
    }

    private void updatePhoto(String userid, File file) {
        Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), getBitmapOption(1));
        saveBitmapFile(file.getPath(), bitmap);

        HttpManager.getInstance().updatePhoto(userid, file).subscribe(new BaseSubscriber(new HttpOnNextListener<UpdatePhotoBean>() {
            @Override
            public void onNext(UpdatePhotoBean o) {
                GlideUtils.circleImage1(PersonalDataActivity.this, o.getImg(), photoIv);
            }
        }, this));
    }

    private void personalData(String userid) {
        HttpManager.getInstance().personalData(userid).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<PersonalDataBean>() {
            @Override
            public void onNext(PersonalDataBean o) {
                setViewData(o);
            }
        }, this));
    }

    private void setViewData(PersonalDataBean o) {
        GlideUtils.circleImage(this, o.getUserImg(), photoIv);
        meunLayout.setBean(o);
        nameTv.setText(o.getName());
    }

    private BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }

    public void saveBitmapFile(String path, Bitmap bitmap) {
        File file = new File(path);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateInfo(){
        if(meunLayout.checkInfo()){
            PersonalDataBean beans = meunLayout.getUserInfo();
            HttpManager.getInstance().updateInfo(userid, beans.getName(), beans.getPhone(), beans.getEmail(), beans.getClo()).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<UpdateInfoBean>() {
                @Override
                public void onNext(UpdateInfoBean o) {
                    if (o.getResult().equals("1")) {
                        ToastUtils.showToast(PersonalDataActivity.this, "修改成功");
                        finish();
                    }
                }
            }, this));
        }
    }

    @Override
    public void showMsg(String msg) {
        super.showMsg(msg);
        if(pd!=null)
            pd.dismiss();
//        ToastUtils.showToast(PersonalDataActivity.this,"网络中断，请检查您的网络状态");
    }
}